#include <iostream>
#include <hv/TcpServer.h>
#include <fmt/core.h>

using namespace hv;

int main(int argc, char *argv[]) {
    if (argc < 2) {
        fmt::print("Usage: {} port\n", argv[0]);
        return -10;
    }

    int port = atoi(argv[1]);

    TcpServer srv;
    int listenfd = srv.createsocket(port);
    if (listenfd < 0) {
        return -20;
    }

    fmt::print("server listen on port {}, listenfd = {} ...\n", port, listenfd);
    srv.onConnection = [](const SocketChannelPtr &channel) {
        std::string peeraddr = channel->peeraddr();
        if (channel->isConnected()) {
            fmt::print("{} connected! connfd = {}\n", peeraddr.c_str(), channel->fd());
        } else {
            fmt::print("{} disconnected! connfd = {}\n", peeraddr.c_str(), channel->fd());
        }
    };
    srv.onMessage = [](const SocketChannelPtr &channel, Buffer *buf) {
        // echo
        printf("< %.*s\n", (int) buf->size(), (char *) buf->data());
        channel->write(buf);
    };
    srv.onWriteComplete = [](const SocketChannelPtr &channel, Buffer *buf) {
        printf("> %.*s\n", (int) buf->size(), (char *) buf->data());
    };
    srv.setThreadNum(4);
    srv.start();

    // press Enter to stop
    while (getchar() != '\n');
    return 0;
}
